<template>
  <div class="modal fade"
       id="reportModelModal"
       tabindex="-1"
       role="dialog"
       aria-labelledby="myModalLabel"
       aria-hidden="true"
       style="z-index: 1000">
    <div class="modal-dialog"
         style="width: 950px;">
      <div class="modal-content"
           style="text-align: center;width: 950px;">
        <div class="modal-header">
          <button type="button"
                  class="close"
                  data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
          <h4 class="modal-title"
              id="myModalLabel">楼盘报备模板</h4>
        </div>
        <div class="modal-body">
          <div class="form-horizontal">
            <div class="form-group">
              <div class="model-left">
                <ul class="modelList">
                  <li>
                    <div style="float:left;width: 120px;text-align: left"><span># &nbsp;</span>名称</div>
                    <!--<div style="float:left;width: 150px;display:none">别名</div>-->
                    <!--<div style="float:left;width: 60px">显示</div>-->
                    <div style="float:right;width: 120px;text-align: right;">操作</div>
                  </li>
                  <li v-for="(r,index) in reportModelList">
                    <div style="float:left;width: 120px;text-align: left"><span>{{index+1}} &nbsp;</span>{{r.modelColumn}}</div>
                    <div style="float:left;width: 120px; display:none;">
                      <input type="text"
                             class="text-column"
                             v-if="!r.show"
                             v-model="r.modelAlias" />
                      <label v-if="false"
                             v-model="r.modelAlias">{{r.modelAlias}}</label>
                    </div>
                    <div style="float:right;width: 100px;"
                         v-show="r.modelType == 1 && (r.modelColumn == '预计到访时间' || r.modelColumn == '报备推荐人')">
                      <el-select v-model="r.showFlag"
                                 size="mini"
                                 placeholder="请选择"
                                 @change='modelStatusChange($event, r)'>
                        <el-option v-for="item in showStatusList"
                                   :key="item.value"
                                   :label="item.name"
                                   :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <!--
                                        <div style="float:left;width: 60px;">
                                            <i-switch size="large" :disabled="r.show" :value="r.showFlag=='1'" v-model="r.showFlag">
                                                <span slot="open">显示</span>
                                                <span slot="close">隐藏</span>
                                            </i-switch>
                                        </div>
                                        -->
                    <div style="float:right;width: 140px;text-align: right;">
                      <!--<Icon type="ios-construct" v-if="r.show" size="24" @click="edit(r)"/>-->
                      <!--<Icon type="ios-checkmark-circle" style="color:#1f8400" v-if="!r.show" size="24" @click="confirmEdit(r)"/>-->
                      <!--<Icon type="ios-undo" v-if="!r.show" size="24" @click="cancelEdit(r)"/>-->
                      <!--<Icon type="ios-arrow-dropdown-circle" size="24" @click="move(r,1)"/>-->
                      <!--<Icon type="ios-arrow-dropup-circle" size="24" @click="move(r,0)"/>-->
                      <Icon type="ios-remove-circle"
                            class="action-button"
                            @click="removeModel(index)"
                            size="24"
                            v-show="r.modelType == 2" />
                    </div>
                  </li>
                </ul>
                <ul class="modelList">
                  <li style="border: none;margin: 10px 0;">
                    <div style="float:left;width: 175px;text-align: left"><Input v-model="reportModel.modelColumn"
                             placeholder="名称"
                             style="width: 170px" /></div>
                    <div style="float:left;width: 175px;display: none;">
                      <Input v-model="reportModel.modelAlias"
                             placeholder="别名"
                             style="width: 170px" />
                    </div>
                    <!--
                                        <div style="float:left;width: 60px;display: ">
                                            <i-switch size="large" v-model="reportModel.showFlag">
                                                <span slot="open">显示</span>
                                                <span slot="close">隐藏</span>
                                            </i-switch>
                                        </div>
                                        -->
                    <div style="float:right;width: 40px;text-align: right;">
                      <Icon type="ios-add-circle"
                            class="action-button"
                            @click="addModel" />
                    </div>
                  </li>
                </ul>
                <div class="model-left-tip">注意：若将参数插入报备模板，则经纪人在报备的时候需要填写相关信息</div>
              </div>
              <div class="model-right">
                <div class="model-set">
                  <div class="model-config">
                    <h3>
                      <b>报备信息复制模板配置</b>
                      <i-button size="small"
                                type="primary"
                                @click="paramShow=true"
                                contenteditable="false">
                        插入参数
                      </i-button>
                    </h3>
                    <div class="content-text"
                         contenteditable="true"
                         id="contentText"
                         @keyup.delete="keybordClick"
                         @keyup="setContentShow"
                         @keyup.left="keybordDirection('left')"
                         @keyup.right="keybordDirection('right')"
                         @keyup.up="keybordDirection('up')"
                         @keyup.down="keybordDirection('down')">
                      {{contentShow}}
                    </div>
                    <div style="padding:5px;text-align: center;">
                      <a class="a-btn"
                         @click="setDefaultModel">恢复默认模板</a>
                    </div>
                  </div>
                  <div class="model-view">
                    <h3><b>报备信息复制效果预览</b></h3>
                    <div class="content-text-show"
                         contenteditable="true"
                         readonly
                         v-html="contentShow">
                    </div>
                  </div>
                </div>
                <div class="model-set-info">
                  <h3><span style="color:#E88037">用法教程</span></h3>
                  <div><span style="color:#E88037">第1步：</span>在左边参数库中添加所需要的参数</div>
                  <div><span style="color:#E88037">第2步：</span>在报备信息复制模板配置中手动打入模板文案，在需要填入参数的位置点击“插入参数”</div>
                  <div><span style="color:#E88037">第3步：</span>选择之前添加好的参数，点击确定，该参数即可自动填入</div>
                  <div><span style="color:#E88037">第4步：</span>在右边预览框中确认模板是否正确即可，注意，预览参数为我们模拟的参数，您使用的 时候，会根据报备信息的不同，进行实时变化</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <!--<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>-->
          <!--<button type="button" class="btn checkedBtn" v-show="btnShow">返回</button>-->
          <button type="button"
                  class="btn checkedBtn"
                  @click="setOtherPremises">将设置应用到其他楼盘</button>
          <button type="button"
                  class="btn checkedBtn"
                  @click="updateReportModel">保存设置</button>
        </div>
      </div>
    </div>
    <!-- 参数选择-->
    <Modal v-model="paramShow"
           width="360"
           :styles="{top: '300px'}">
      <p slot="header"
         style="color:#f60;text-align:center">
        <Icon type="information-circled"></Icon>
        <span>选择已添加的参数</span>
      </p>
      <div style="text-align:center">
        <i-select v-model="selectParam"
                  style="width:200px">
          <i-option v-for="item in reportModelList"
                    :value="item">{{ item.modelColumn }}</i-option>
        </i-select>
      </div>
      <div slot="footer">
        <i-button type="error"
                  size="small"
                  long
                  :loading="modal_loading"
                  @click="addParam">确定</i-button>
      </div>
    </Modal>
    <!-- -->
    <!-- 楼盘选择-->
    <Modal v-model="premisesShow"
           width="600"
           :styles="{top: '300px'}">
      <p slot="header"
         style="color:#f60;text-align:center">
        <Icon type="information-circled"></Icon>
        <span>选择应用该模板的楼盘</span>
      </p>
      <div style="text-align:center">
        <i-select v-model="selectPremises"
                  multiple
                  style="width:550px">
          <i-option v-for="item in findPremisesList"
                    :value="item.premisesId">{{ item.premisesName }}</i-option>
        </i-select>
      </div>
      <div slot="footer">
        <i-button type="error"
                  size="small"
                  long
                  :loading="modal_loading"
                  @click="premisesShow=false">确定</i-button>
      </div>
    </Modal>
    <!-- 楼盘选择-->
  </div>
</template>

<script>
import { Modal } from "iview";
export default {
  name: "report-model",
  props: ["reportModelModal"],
  components: {
    Modal
  },
  data() {
    return {
      showStatusList: [
        {
          value: "1",
          name: "必填"
        },
        {
          value: "2",
          name: "选填"
        },
        {
          value: "0",
          name: "不展示"
        }
      ],
      paramShow: false,
      selectParam: "",
      reportModelList: [],
      reportModel: {},
      reportModelView: "\r\n",
      contentShow: "",
      findPremisesList: [],
      selectPremises: [],
      premisesShow: false,
      modelIds: [],
      modelStatusList: []
    };
  },
  mounted() {
    this.findPremisesLists();
  },
  watch: {
    //监听父组件绑定值是否改变
    reportModelModal: {
      handler: function (val, oldVal) {
        this.init();
      },
      //深层监听，若设为true，属性变更时即可触发，若为false，属性无法监听到
      deep: true
    }
  },
  methods: {
    init() {
      var _self = this;
      _self.getModelList(0);
    },
    modelStatusChange(val, info) {
      var _self = this;
      console.log("----------" + info.id);
      if (_self.modelStatusList && _self.modelStatusList.length > 0) {
        var _key = 0;
        for (var i = 0; i < _self.modelStatusList.length; i++) {
          if (_self.modelStatusList[i].id == info.id) {
            _self.modelStatusList[i].showFlag = val;
            _key = 1;
          }
        }
        if (_key == 0) {
          var a = { id: info.id, showFlag: val };
          _self.modelStatusList.push(a);
        }
      } else {
        var a = { id: info.id, showFlag: val };
        _self.modelStatusList.push(a);
      }
    },
    findPremisesLists: function () {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/getCaseMemberList";
      var body = {};
      body.params = {
        userId: window.localStorage.getItem("userId")
      };
      _self.$http.post(url, body).then((response) => {
        _self.findPremisesList = response.body.resData.caseMemberList;
      });
    },
    addModel: function () {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/addReportModel";
      if (!_self.reportModel.modelColumn) {
        layer.msg("名称不能为空");
        return;
      }
      var params = {
        modelColumn: _self.reportModel.modelColumn,
        premisesId: _self.reportModelModal.premisesId,
        modelType: 2,
        showFlag: _self.reportModel.showFlag ? 1 : 0,
        modelAlias: _self.reportModel.modelAlias
      };
      var body = {};
      body.params = params;
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == "1") {
          params.id = body.resData.model.id;
          params.show = true;
          var modelType = body.resData.model.modelType;
          params.modelType = modelType;
          if (modelType == "1") {
            params.showFlag = body.resData.model.showFlag;
          } else {
            params.showFlag = body.resData.model.showFlag == 1 ? true : false;
          }
          _self.reportModelList.push(params);
          _self.showModelText();
          _self.reportModel.modelColumn = "";
        } else {
          layer.msg("添加失败");
        }
      });
    },
    removeModel: function (index) {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/deleteReportModel";
      var params = { id: _self.reportModelList[index].id };
      var body = {};
      body.params = params;
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == "1") {
          _self.reportModelList.splice(index, 1);
          _self.showModelText();
        } else {
          layer.msg("删除失败");
        }
      });
    },
    getModelList(flag) {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/getReportModelList";
      var body = {};
      body.params = { premisesId: _self.reportModelModal.premisesId };
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == "1") {
          for (var i in body.resData.list) {
            body.resData.list[i].show = true;
            //body.resData.list[i].showFlag = body.resData.list[i].showFlag==1?true:false;
          }
          _self.reportModelList = body.resData.list;
          if (flag == 0) {
            _self.getReportModel();
          }
          _self.showModelText();
        } else {
          layer.msg("获取报备模板失败");
        }
      });
    },
    move(model, type) {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/moveReportModelOrder";
      var body = {};
      body.params = {
        id: model.id,
        modelOrder: model.modelOrder,
        premisesId: _self.reportModelModal.premisesId,
        action: type
      };
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == "1") {
          _self.getModelList();
        } else {
          layer.msg(body.errorMsg);
        }
      });
    },
    edit(model) {
      model.tempColumn = model.modelColumn;
      model.show = false;
    },
    cancelEdit(model) {
      model.modelColumn = model.tempColumn;
      model.tempColumn = "";
      model.show = true;
    },
    confirmEdit(r) {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/addReportModel";
      var params = {
        id: r.id,
        premisesId: this.reportModelModal.premisesId,
        showFlag: r.showFlag ? 1 : 0,
        modelAlias: r.modelAlias
      };
      var body = {};
      body.params = params;
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == "1") {
          _self.getModelList();
        } else {
          layer.msg("操作失败");
        }
      });
    },
    showModelText() {
      this.reportModelView = "\r\n";
      for (var i in this.reportModelList) {
        if (!this.reportModelList[i].showFlag) {
          continue;
        }
        if (!this.reportModelList[i].modelAlias) {
          this.reportModelView +=
            this.reportModelList[i].modelColumn + ":******\r\n";
        } else {
          this.reportModelView +=
            this.reportModelList[i].modelAlias + ":******\r\n";
        }
      }
    },
    addParam() {
      //添加参数到配置区this.selectParam;
      var range = window.getSelection();
      var contentText = document.getElementById("contentText");
      if (range.focusNode.parentElement.className == "model-label") {
        this.paramShow = false;
        layer.msg("对不起这样做不合规矩");
        return;
      }

      var html = contentText.innerHTML;
      var tempText =
        '<span class="ql-cursor">﻿</span><span class="model-label" style="color:#f90;" data-paramid="' +
        this.selectParam.id +
        '">[' +
        this.selectParam.modelColumn +
        ']</span><span class="ql-cursor">﻿</span>';

      console.log(range);
      this.modelIds.push(this.selectParam.id);
      let className = range.focusNode.parentElement.className;
      let focusClassName = range.focusNode.className;
      let nodeT = document.createElement("span");
      nodeT.innerHTML = tempText;
      let domRange = document.getSelection().getRangeAt(0);
      console.log(domRange);
      if (this.checkIsContext()) {
        domRange.insertNode(nodeT);
        this.setCousor(nodeT);
      } else {
        this.setCousor(contentText);
        this.insertHTML(tempText);
      }
      // if(className == 'model-label'  || className == 'ql-cursor' ){
      //     //焦点不再编辑框内
      //     console.log("step 01")
      //     // contentText.innerHTML = html + tempText;
      //     domRange.insertNode(nodeT);
      // }else if(className == 'content-text'){
      //     //如果父节点是div，本身又是text就在当前节点插入元素
      //     console.log("step 02")
      //     domRange.insertNode(nodeT);
      //     // nodeT.focus();
      //
      // } else if(focusClassName == 'content-text'){
      //     //直接在当前光标处添加节点
      //     console.log("step 03")
      //     domRange.insertNode(nodeT);
      //     // nodeT.focus();
      // } else{
      //     console.log("step 04")
      //     this.setCousor(contentText);
      //     this.insertHTML(tempText);
      // }

      this.paramShow = false;
      // this.setCousor(contentText);
      this.setContentShow();
    },
    keybordClick(e) {
      console.log(e);
      //backspace delete 单独写事件处理
      var range = window.getSelection();
      var node;
      console.log(range);
      if (e.code == "Delete") {
        node = range.focusNode.nextElementSibling;
      } else if (e.code == "Backspace") {
        node = range.focusNode.parentNode;
      }
      if (node.nodeName == "SPAN") {
        if (node.className == "model-label") {
          //移除id
          var modelId = window.getSelection().focusNode.parentElement.dataset[
            "paramid"
          ];
          this.modelIds.splice(modelId);
          node.parentNode.removeChild(node);
          // document.getElementById("contentText").removeChild(node);
        }
      }
      this.setContentShow();
    },
    setCousor(contentText) {
      if (window.getSelection) {
        //ie11 10 9 ff safari
        contentText.focus(); //解决ff不获取焦点无法定位问题
        var range = window.getSelection(); //创建range
        range.selectAllChildren(contentText); //range 选择obj下所有子内容
        range.collapseToEnd(); //光标移至最后
      } else if (document.selection) {
        //ie10 9 8 7 6 5
        var range = document.selection.createRange(); //创建选择对象
        //var range = document.body.createTextRange();
        range.moveToElementText(contentText); //range定位到obj
        range.collapse(false); //光标移至最后
        range.select();
      }
    },
    setContentShow() {
      //设置预览效果
      var text = document.getElementById("contentText").innerHTML;
      text = text.replace(/\[报备项目\]/g, "天相国际");
      text = text.replace(/\[客户姓名\]/g, "李四");
      text = text.replace(/\[客户性别\]/g, "男");
      text = text.replace(/\[客户号码\]/g, "15812345678");
      text = text.replace(/\[分销公司\]/g, "太平洋公司");
      text = text.replace(/\[中介经纪人\]/g, "张三");
      text = text.replace(/\[经纪人电话\]/g, "18512345678");
      text = text.replace(/\[预计到访时间\]/g, "2019-01-01");
      text = text.replace(/\[报备时间\]/g, "2019-01-01");
      text = text.replace(/\[报备推荐人\]/g, "小王");
      this.contentShow = text;
    },
    updateReportModel() {
      layer.load(0, { shade: [0.2, "#000"] }); //弹出加载层
      var params = document.getElementById("contentText");
      var content = {
        content: params.innerHTML,
        contentParams: params.innerText,
        premisesId: this.reportModelModal.premisesId
        // modelIds:this.modelIds
      };
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/batchUpdateReportModel";
      var params = {
        sourceId: this.reportModelModal.premisesId,
        targetIds: this.selectPremises,
        content: content,
        modelStatusList: _self.modelStatusList
      };
      var body = {};
      body.params = params;
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == "1") {
          _self.getModelList();
          $("#reportModelModal").modal("hide");
          layer.msg("保存成功");
          layer.closeAll("loading");
          _self.selectPremises = [];
        } else {
          layer.msg("操作失败");
          layer.closeAll("loading");
        }
        layer.closeAll("loading");
      });
    },
    insertHTML(text) {
      var contentText = document.getElementById("contentText");
      var obj = contentText[0];
      var range, node;
      // if (!obj.hasFocus()) {
      //     obj.focus();
      // }
      //如果光标不在编辑区内就不再添加
      if (document.selection && document.selection.createRange) {
        this.setCousor(contentText);
        document.selection.createRange().pasteHTML(text);
        this.setCousor(contentText);
      } else if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        range.collapse(false);
        node = range.createContextualFragment(text);
        var c = node.lastChild;
        range.insertNode(node);
        if (c) {
          range.setEndAfter(c);
          range.setStartAfter(c);
        }
        var j = window.getSelection();
        j.removeAllRanges();
        j.addRange(range);
        this.setCousor(contentText);
      }
    },
    setDefaultModel() {
      //如果没有设置基础模板就显示默认的模板
      var text = "";
      for (var i in this.reportModelList) {
        text +=
          "<div>" +
          this.reportModelList[i].modelColumn +
          '：<span class="ql-cursor">﻿</span><span class="model-label"  style="color:#f90;"data-paramid="' +
          this.reportModelList[i].id +
          '">[' +
          this.reportModelList[i].modelColumn +
          ']</span></span><span class="ql-cursor">﻿\r\n</span></div> ';
      }
      document.getElementById("contentText").innerHTML = text;
      this.setContentShow();
    },
    getReportModel() {
      var _self = this;
      //获取楼盘报备模板 getReportModelContent
      var url = this.utilHelper.apiUrl + "/api/getReportModelContent";
      var body = {};
      body.params = {
        premisesId: _self.reportModelModal.premisesId
      };
      _self.$http.post(url, body).then((response) => {
        var body = response.body;
        if (body.result == "1") {
          if (body.resData.content && body.resData.content.content) {
            //若存在报备模板则则设置楼盘
            document.getElementById("contentText").innerHTML =
              body.resData.content.content;
          } else {
            _self.setDefaultModel();
          }
        } else {
          _self.setDefaultModel();
        }
        _self.setContentShow();
      });
    },
    /**
     * 方向键操作
     */
    keybordDirection(direction) {
      var range = window.getSelection();
      if (range.focusNode.parentNode.nodeName == "SPAN") {
        if (range.focusNode.parentNode.className == "model-label") {
          if (direction == "left") {
            var preNode = range.focusNode.parentElement.previousElementSibling;
          } else {
            var preNode = range.focusNode.parentElement.nextElementSibling;
          }
          this.setCousor(preNode);
        }
      }
    },
    //判断是否在编辑区域内
    checkIsContext() {
      var range = window.getSelection().focusNode;
      if (!range) {
        return false;
      }
      let parentnode = range.parentElement;
      //最多向上查找10次,找不到默认添加到末尾
      for (var i = 0; i < 10; i++) {
        if (!parentnode.className && !parentnode.id) {
          if (!parentnode.nodeName && parentnode.nodeName == "HTML") {
            return false;
          }
          parentnode = parentnode.parentNode;
          continue;
        }
        if (
          parentnode.className == "model-label" ||
          parentnode.className == "ql-cursor" ||
          parentnode.className == "content-text" ||
          range.className == "content-text"
        ) {
          return true;
        } else if (
          parentnode.className == "modal-content" ||
          parentnode.id == "app"
        ) {
          return false;
        } else {
          parentnode = parentnode.parentNode;
        }
      }
      return false;
    },
    setOtherPremises() {
      var _self = this;
      _self.premisesShow = true;
    }
  }
};
</script>

<style scoped>
.action-button {
  font-size: 32px;
  color: #f87242;
}
.col {
  text-align: left;
}
.modelList {
  margin-left: 20px;
  width: 400px;
}
.modelList li {
  width: 399px;
  height: 35px;
  line-height: 30px;
  border-bottom: 1px dashed #bbbbbb;
}
.modelList li label {
  text-align: left;
}
.modelList li icon {
  text-align: right;
}
.text-column {
  width: 120px;
  height: 20px;
}
.model-left {
  width: 430px;
  height: 570px;
  float: left;
  border-right: 1px solid #bbbbbb;
  position: relative;
}
.model-left-tip {
  position: absolute;
  bottom: 5px;
  left: 5px;
}
.model-right {
  width: 510px;
  height: 570px;
  float: left;
  padding: 0 15px;
  text-align: left;
}
.model-right h3 {
  margin-bottom: 15px;
}
.model-set {
  width: 510px;
  height: 380px;
}
.model-set h3 {
  height: 24px;
}
.model-config {
  float: left;
  width: 230px;
}
.model-view {
  float: left;
  width: 230px;
}
.content-text {
  border-radius: 3px;
  border: 1px solid #bbbbbb;
  padding: 5px;
  width: 223px;
  min-height: 300px;
  word-break: keep-all;
}
.content-text-show {
  border-radius: 3px;
  border: 1px solid #bbbbbb;
  padding: 5px;
  width: 223px;
  min-height: 300px;
  word-break: keep-all;
}
.model-label {
  color: #f90;
}
.content-view {
  border-radius: 3px;
  border: 1px solid #bbbbbb;
  padding: 5px;
  width: 223px;
  min-height: 300px;
  background: #f3f3f3;
}
.model-set-info {
  margin-top: 30px;
}
.model-set-info h3 {
  text-align: left;
}
.a-btn {
  display: block;
  background-color: #f90;
  height: 30px;
  width: 150px;
  line-height: 30px;
  font-size: 14px;
  color: white;
  border-radius: 5px;
}
</style>
